#include <iostream>
#include <unistd.h>
#include <cstring>
#include <sys/wait.h>

using namespace std;
int main()
{
    int pipefd[2] = {0};
    if (pipe(pipefd) != 0)
    {
        cerr << "pipe error" << endl;
        return 1;
    }

    pid_t id = fork();
    if (id < 0)
    {
        cerr << "fork error" << endl;
        return 2;
    }
    if (id == 0)
    {
        // child , 读取管道数据，关闭写端
        close(pipefd[1]);
#define NUM 1024
        char buffer[NUM];
        while (true)
        {
            memset(buffer, 0, sizeof(buffer));
            ssize_t s = read(pipefd[0], buffer, sizeof(buffer) - 1);
            if (s > 0) //读取成功
            {
                buffer[s] = '\0';
                cout << "子进程收到消息：" << buffer << endl;
            }
            else if (s == 0)
            {
                cout << "父进程写入结束，子进程退出" << endl;
                break;
            }
            else
            {
                // do nothing
            }
        }
        close(pipefd[0]);
        exit(0);
    }
    else
    {
        // parent , 写入管道数据，关闭读端
        close(pipefd[0]);
        const char *msg = "I am father\n";
        int cnt = 1;
        while (cnt++ <= 5)
        {
            char sendbuffer[1024];
            sprintf(sendbuffer, "%s", msg);
            write(pipefd[1], sendbuffer, strlen(sendbuffer));
        }
        close(pipefd[1]);
        cout << "父进程写入结束" << endl;
    }
    pid_t res = waitpid(id, nullptr, 0);
    if (res > 0)
    {
        cout << "等待子进程退出成功" << endl;
    }
    return 0;
}